

package com.hazelcast.topic.impl;

import com.hazelcast.config.ListenerConfig;
import com.hazelcast.config.TopicConfig;
import com.hazelcast.core.HazelcastInstanceAware;
import com.hazelcast.internal.monitor.impl.LocalTopicStatsImpl;
import com.hazelcast.internal.namespace.NamespaceUtil;
import com.hazelcast.internal.nio.ClassLoaderUtil;
import com.hazelcast.internal.util.ExceptionUtil;
import com.hazelcast.spi.impl.AbstractDistributedObject;
import com.hazelcast.spi.impl.InitializingObject;
import com.hazelcast.spi.impl.NodeEngine;
import com.hazelcast.spi.impl.operationservice.OperationService;
import com.hazelcast.topic.LocalTopicStats;
import com.hazelcast.topic.MessageListener;

import javax.annotation.Nonnull;
import java.util.UUID;

public abstract class TopicProxySupport extends AbstractDistributedObject<TopicService> implements InitializingObject {

    private final String name;
    private final TopicService topicService;
    private final LocalTopicStatsImpl topicStats;
    private final OperationService operationService;
    private final int partitionId;
    private boolean multithreaded;
    private ClassLoader classLoader;

    protected TopicProxySupport(String name, NodeEngine nodeEngine, TopicService service) {
        super(nodeEngine, service);
        this.name = name;
        this.topicService = service;
        this.topicStats = topicService.getLocalTopicStats(name);
        this.operationService = nodeEngine.getOperationService();
        this.partitionId = nodeEngine.getPartitionService().getPartitionId(getNameAsPartitionAwareData());
    }

    @Override
    public void initialize() {
        NodeEngine nodeEngine = getNodeEngine();
        TopicConfig config = nodeEngine.getConfig().findTopicConfig(name);
        multithreaded = config.isMultiThreadingEnabled();
        classLoader = NamespaceUtil.getClassLoaderForNamespace(nodeEngine, config.getUserCodeNamespace());
        for (ListenerConfig listenerConfig : config.getMessageListenerConfigs()) {
            initialize(listenerConfig);
        }
    }

    private void initialize(ListenerConfig listenerConfig) {
        MessageListener listener = loadListener(listenerConfig);
        if (listener == null) {
            return;
        }

        addMessageListenerInternal(listener);
    }

    private MessageListener loadListener(ListenerConfig listenerConfig) {
        try {
            MessageListener listener = (MessageListener) listenerConfig.getImplementation();
            if (listener == null && listenerConfig.getClassName() != null) {
                listener = ClassLoaderUtil.newInstance(classLoader, listenerConfig.getClassName());
            }
            return listener;
        } catch (Exception e) {
            throw ExceptionUtil.rethrow(e);
        }
    }

    public LocalTopicStats getLocalTopicStatsInternal() {
        return topicService.getLocalTopicStats(name);
    }

    /**
     * Publishes the message and increases the local statistics
     * for the number of published messages.
     *
     * @param message the message to be published
     */
    public void publishInternal(@Nonnull Object message) {
        topicService.publishMessage(name, message, multithreaded);
        topicStats.incrementPublishes();
    }

    public @Nonnull UUID addMessageListenerInternal(@Nonnull MessageListener listener) {
        if (listener instanceof HazelcastInstanceAware aware) {
            aware.setHazelcastInstance(getNodeEngine().getHazelcastInstance());
        }
        return topicService.addMessageListener(name, listener);
    }

    public boolean removeMessageListenerInternal(@Nonnull UUID registrationId) {
        return topicService.removeMessageListener(name, registrationId);
    }

    @Override
    public String getServiceName() {
        return TopicService.SERVICE_NAME;
    }

    @Override
    public String getName() {
        return name;
    }
}
